<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ include file="../common/include.jsp"%>
<html>
<head>
<title>代码生成信息</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link href="<%=basePath%>vendors/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="<%=basePath%>vendors/font-awesome/css/font-awesome.min.css"
	rel="stylesheet">
<link href="<%=basePath%>vendors/animate/css/animate.css" rel="stylesheet">
<link href="<%=basePath%>vendors/iCheck/custom.css" rel="stylesheet">
<link href="<%=basePath%>vendors/datepicker/datepicker3.css" rel="stylesheet">
<!-- jqgrid-->
<link href="<%=basePath%>vendors/jqgrid/css/ui.jqgrid-bootstrap.css" rel="stylesheet">
<!-- Sweet Alert -->
<link href="<%=basePath%>vendors/sweetalert/sweetalert.css" rel="stylesheet">
<link href="<%=basePath%>common/css/style.css" rel="stylesheet">
<!-- 由于使用了自定义标签，jquery必须在之前 -->
<!-- 全局js -->
<script src="<%=basePath%>vendors/jquery/js/jquery.min.js"></script>
<script src="<%=basePath%>vendors/bootstrap/js/bootstrap.min.js"></script>
<!-- jqGrid -->
<script src="<%=basePath%>vendors/jqgrid/js/i18n/grid.locale-cn.js"></script>
<script src="<%=basePath%>vendors/jqgrid/js/jquery.jqGrid.min.js"></script>
<script src="<%=basePath%>vendors/jqgrid/plugins/jquery.tablednd.js"></script>
<script src="<%=basePath%>vendors/vue/vue.min.js"></script>
<!-- iCheck -->
<script src="<%=basePath%>vendors/iCheck/icheck.min.js"></script>
<!-- Sweet alert -->
<script src="<%=basePath%>common/js/curdtools_jqgrid.js"></script>
<script src="<%=basePath%>vendors/layer/layer.min.js"></script>
<script src="<%=basePath%>common/js/common.js"></script>
</head>
<body class="white-bg">
	<div class="ibox-content" id="rrapp" v-cloak>
       <form id="inputForm" name="inputForm">
       <input type="hidden" id="id" name="id" value="${tableEntity.id}"/>
       <input type="hidden" id="columnList" name="columnList"/>
		<table class="table table-bordered  table-condensed dataTables-example dataTable no-footer">
		   <tbody>
		       <tr>
		         <td  class="width-15 active text-right">	
		              <label><font color="red">*</font>表名:</label>
		         </td>
		         <td class="width-35">
		               <input id="tableName" name="tableName" class="form-control " value="${tableEntity.tableName}"/>
		         </td>
		         <td  class="width-15 active text-right">	
		              <label><font color="red">*</font>类名:</label>
		         </td>
		         <td class="width-35">
		               <input id="className" name="className" class="form-control " placeholder="请输入类名" value="${tableEntity.className}"/>
		         </td>
		      </tr>
		      <tr>
		         <td  class="width-15 active text-right">	<label><font color="red">*</font>表类型:</label></td>
			     <td  class="width-35" >
			             <select id="tableType" name="tableType" class="form-control">
			             	<option value="1">单表</option>
			             </select>
			     </td>
		         <td  class="width-15 active">
		              <label class="pull-right">备注:</label>
		         </td>
		         <td class="width-35">
		              <textarea id="remarks" name="remarks" rows="2" maxlength="200" class="form-control ">${tableEntity.remarks}</textarea>
		         </td>
		      </tr>
		   </tbody>
		   </table>   
	</form>
	<div id="javaTypeForm" style="display:none;">
	     <div class="form-horizontal wrapper wrapper-content">
              <div class="form-group">
                  <label class="col-sm-3 control-label">包名：</label>
                  <div class="col-sm-8">
                      <input id="packagePath" name="packagePath" type="text" placeholder="包名" class="form-control"> 
                      <span class="help-block m-b-none">请输入包名</span>
                  </div>
              </div>
              <div class="form-group">
                  <label class="col-sm-3 control-label">类名：</label>
                  <div class="col-sm-8">
                      <input id="className" name="className"  type="text" placeholder="类名" class="form-control">
                      <span class="help-block m-b-none">请输入类名</span>
                  </div>
              </div>
          </div>
	</div>

	    <button class="btn btn-success" onClick="save();"><i class="fa fa-plus"> 保存</i></button>
		<button class="btn btn-info" onClick="codegen();"><i class="fa fa-minus"> 代码生成</i> </button>	
	    <button class="btn btn-white btn-sm" onClick="return addRowData('attributeInfoTable')"><i class="fa fa-plus"> 增加</i></button>
		<button class="btn btn-warning" onClick="return delRowData('attributeInfoTable')"><i class="fa fa-minus"> 删除</i> </button>
	    <div class="row">
                <div class="tabs-container">
                    <ul class="nav nav-tabs">
                        <li class="active"><a data-toggle="tab" href="#tab_dbinfo" aria-expanded="true">数据库属性</a></li>
                        <li class=""><a data-toggle="tab" href="#tab_pageinfo" aria-expanded="false">页面属性</a></li>
                        <li class=""><a data-toggle="tab" href="#tab_validinfo" aria-expanded="false">页面校验</a></li>
                    </ul>
                    <div class="tab-content" >
                        <div id="tab_dbinfo" class="tab-pane active">
                            <div class="panel-body">
                                <div class="jqGrid_wrapper">
		                            <table id="attributeInfoTable"></table>
		                        </div>
                            </div>
                        </div>
                        <div id="tab_pageinfo" class="tab-pane">
                            <div class="panel-body">
                                 <div class="jqGrid_wrapper">
		                            <table id="pageInfoTable"></table>
		                        </div>
                            </div>
                        </div>
                        <div id="tab_validinfo" class="tab-pane">
                            <div class="panel-body">
                                 <div class="jqGrid_wrapper">
		                            <table id="validInfoTable"></table>
		                        </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
	</div>
</body>

<script type="application/javascript">
var javaField=['String','Double','Text','Date','Blob','Short','Integer','Boolean','User','this'];
var baseJavaType="String:String;Double:Double;Text:Text;Date:Date;Blob:Blob;Short:Short;Integer:Integer;Boolean:Boolean;User:User;this:this";
var typeNames="VARCHAR:VARCHAR;TINYINT:TINYINT;SMALLINT:SMALLINT;MEDIUMINT:MEDIUMINT;INT:INT;INTEGER:INTEGER;BIGINT:BIGINT;FLOAT:FLOAT;DOUBLE:DOUBLE;DECIMAL:DECIMAL;DATE:DATE;TIME:TIME;YEAR:YEAR;DATETIME:DATETIME;TIMESTAMP:TIMESTAMP;BINARY:BINARY;VARBINARY:VARBINARY;CHAR:CHAR;TINYBLOB:TINYBLOB;TINYTEXT:TINYTEXT;BLOB:BLOB;TEXT:TEXT;MEDIUMBLOB:MEDIUMBLOB;MEDIUMTEXT:MEDIUMTEXT;LONGBLOB:LONGBLOB;LONGTEXT:LONGTEXT";
var extendTypes="other:自定义JAVA类型";
var javaTypeConf=baseJavaType+extendTypes;
var initTableDataStr = ${columns};
var initTableData = eval(initTableDataStr);

function resizeGrid(){
    $("#attributeInfoTable").setGridWidth($(window).width()*0.99-28);
    $("#pageInfoTable").setGridWidth($(window).width()*0.99-28);
    $("#validInfoTable").setGridWidth($(window).width()*0.99-28);
}

function initGrid(girdid,colModel,data){
	 //初始化用户列表
 $("#"+girdid).jqGrid({
         datatype: "local",
		 data: data,
        height: 450,
        editurl: 'clientArray',
        jsonReader : {  
            root:"results",  
            page: "page",  
            total: "totalPage",  
            records: "total"  
        },
        gridComplete: function() {//表格生成完成后的回调函数。  
       	 setGridEdit(girdid);
        },
        viewrecords: true,
        colModel:colModel,
        autowidth: false,
        multiselect:true,
        shrinkToFit: true,
        sortable:true,
        rownumbers: true,
        rownumWidth: 35,
        altRows: true
    });
}

function setGridEdit(gridId){
	 var gridObject = $("#"+gridId);  
	 var rowIds = gridObject.jqGrid('getDataIDs');        //返回当前grid里所有数据的id  
        for(var i=0;i < rowIds.length;i++){  
        	 var rowid=rowIds[i];
        	 gridObject.editRow(rowid, true); 
        }
	}
	
$(document).ready(function () {
	 initTable(initTableData);
	 resizeGrid();
	   $(window).resize(function(){   
		   resizeGrid();
	    });
	   $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
		   resizeGrid();
	   });		 
	 initListener();
});

function initListener(){
	//通过on事件监听数据的变化
	$("#attributeInfoTable").on('input',function(e){  
		   var element =event.target;
		   var inputName=$(element).attr("name");
		   if(inputName=='columnName'||inputName=='remarks'){
			    var rowid = $(element).attr("rowid");
			    var value=$(element).val();
			    //动态的更改行
			    var data=getGridRowData("pageInfoTable",rowid);
			    data[inputName]=value;
			    $("#pageInfoTable").jqGrid("setRowData", rowid, data); 
			    //动态的更改行
			    var datas=getRowDatas("pageInfoTable",true);
			    //刷新
			    //传入查询条件参数  
			    $("#pageInfoTable").jqGrid('setGridParam',{  
			    	data:datas 
			    }).trigger("reloadGrid"); //重新载入      
			    //传入查询条件参数  
			    $("#validInfoTable").jqGrid('setGridParam',{  
			    	data:datas 
			    }).trigger("reloadGrid"); //重新载入      
		   }
		   
	}); 
}

function initTable(data){
	 var attributeColModel=[
			{ label: '字段名称', name: 'columnName', width: 100,  editable: true,editrules: {
             required: true
         }},
			{ label: '字段备注', name: 'remarks', width: 120, editable: true,editrules: {
             required: true
         }},
			{ label: '字段类型', name: 'typeName', width: 100, formatter:'select', editable: true,
			    edittype: "select",
			    editoptions:{value:typeNames}
			},
			{ label: '字段长度', name: 'columnSize', width: 60, editable: true,editrules: {
				number: true,
             minValue: 1,
             required: true
         }},
			{ label: '小数点', name: 'decimalDigits', width: 50, editable: true,editrules: {
				number: true,
             minValue: 0,
             maxValue: 2,
             required: false
         }},
			{ label: '默认值', name: 'columnDef', width: 50, editable: true},
			{ label: 'JAVA类型', name: 'javaType', width: 120,formatter:'select', editable: true,
			    edittype: "select",
			    editoptions: {
			        value:javaTypeConf
			        , dataEvents: [
			                       { type: 'change',          //下拉选择的时候
			                           fn: function(e) {
			                        	   var selectValue=this.value;
			                        	   if($.inArray(selectValue, javaField)=='-1'){
			                        		   var targetId="select#"+e.target.id;
				                               var target = $(targetId);//获取下面下拉框javaType对象
				                               //target.append("<option role=\"option\" value=\"sdfs\">sdfsdf</option>");  
				                               var javaTypeForm=$("#javaTypeForm").clone();
				                               javaTypeForm.attr("id", "javaTypeItem"); ///必须加入，否则id会重复，导致操纵时混乱
				                               if(selectValue!=undefined&&selectValue!=''){
				                            	   var values=selectValue.split('|');
				                            	   if(values.length==2){
					                               	   javaTypeForm.find("#packagePath").attr("value",values[0]);
					                              	   javaTypeForm.find("#className").attr("value",values[1]);
				                            	   }
				                               }
				                               javaTypeForm.find("#packagePath").attr("id", "packagePathItem");
				                               javaTypeForm.find("#className").attr("id", "classNameItem");
				                               
				                               var content=javaTypeForm.html();
				                               //在这里面输入任何合法的js语句
				                               top.layer.open({
				                                 type: 1 //Page层类型
				                                 ,area: ['500px', '300px']
				                                 ,title: '自定义JAVA类型'
				                                 ,shade: 0.6 //遮罩透明度
				                                 ,maxmin: true //允许全屏最小化
				                                 ,anim: 1, //0-6的动画形式，-1不开启
				                                 content:content,
				                                 btn: ['确定', '关闭'],
				         					     yes: function(index, layero){ //或者使用btn1
				         					    	 var packagePath=layero.find("#packagePathItem").val();
				         					    	 var className=layero.find("#classNameItem").val();
				         					    	
				         					    	 if(packagePath==undefined||packagePath==''){
				         					    		 top.layer.tips('请填写包名！', '#packagePathItem');
				         					    		 return false;
				         					    	 }
				         					    	 if(className==undefined||className==''){
				         					    		top.layer.tips('请填写类名！', '#classNameItem');
				         					    		return false;
				         					    	 }
				         					    	 //类名不能为已经存在的基础类型
				         					    	 if($.inArray(className, javaField)!='-1'){
				         					    		top.layer.tips('类名不能为已经存在的基础类型！', '#classNameItem');
				         					    		return false;
				         					    	 }
				         					    	 var realPath=packagePath+"|"+className;
				         					    	 var extend=realPath+":"+className;
				         					    	 if(javaTypeConf.indexOf(realPath)==-1){
				         					    		javaTypeConf+=";"+extend;
				         					    		target.append("<option role=\"option\" value=\""+realPath+"\">"+className+"</option>");
				         					    		$("#attributeInfoTable").setColProp('javaType',{editoptions:{value:javaTypeConf}});
				         					    	 }
				         					    	 //设置选中最后
				         					    	 target.val(realPath);
				         					    	 top.layer.close(index);
				         					    	 
				         					     },
				         			    	     cancel: function(index){}
				                               });    
			                        	   }
			                        	    
			                           }
			                       }
			                    ]
			},editrules: {
             required: true
         }},
			{ label: 'JAVA属性名称', name: 'javaField', width: 120, editable: true,editrules: {
             required: true
         }},
         { label: '主表', name: 'foreignTable', width: 120, editable: true,
        	 required: false
		 },
         { label: '主键', name: 'parmaryKey', width: 40, editable: true,
                 edittype: "checkbox",
                 editoptions: {
                     value: "1:0"
         }},
         { label: '空值', name: 'isNullable', width: 40, editable: true,
             edittype: "checkbox",
             editoptions: {
             	value: "1:0"
        }}
	];
	 
	 initGrid('attributeInfoTable',attributeColModel,data);
	 var pageInfoColModel=[
			{ label: '字段名称', name: 'columnName', width: 100},
			{ label: '字段备注', name: 'remarks', width: 120},
			{ label: '表单', name: 'isForm', width: 50, editable: true,
			        edittype: "checkbox",
			        editoptions: {
			            value: "1:0"
			}},
			{ label: '查询', name: 'isQuery', width: 50, editable: true,
			        edittype: "checkbox",
			        editoptions: {
			            value: "1:0"
			}},
			{ label: '列表', name: 'isList', width: 50, editable: true,
			        edittype: "checkbox",
			        editoptions: {
			            value: "1:0"
			}},
			{ label: '查询方式', name: 'queryType', width: 100, formatter:'select', editable: true,
			    edittype: "select",
			    editoptions: {
			        value: "eq:等于;ne:不等于;gt:大于;ge:大于等于;le:小于等于;isNull:是否为空;isNotNull:非空;in:包含;notIn:不包含;between:between;prefixLike:前缀模糊匹配;prefixNotLike:前缀模糊不匹配;suffixLike:后缀模糊匹配;suffixNotLike:后缀模糊不匹配;like:模糊匹配;notLike:不匹配"
			}},
			{ label: '查询模式', name: 'queryModel', width: 100, formatter:'select', editable: true,
			    edittype: "select",
			    editoptions: {
			        value: "input:input;select:select;radio:radio;checkbox:checkbox;date:date"
			}},
			{ label: '显示表单类型', name: 'formType', width: 120, formatter:'select', editable: true,
			    edittype: "select",
			    editoptions: {
			        value: "input:单行文本;textarea:多行文本;select:下拉选项;radiobox:单选按钮;checkbox:复选框;dateselect:日期选择;editor:编辑器;fileinput:文件上传;avatarinput:头像上传"
			}},
			{ label: '字典类型', name: 'dictGroup', width: 120, editable: true}
	];

	initGrid('pageInfoTable',pageInfoColModel,data);

	var validInfoColModel=[
					{ label: '字段名称', name: 'columnName', width: 120},
					{ label: '字段备注', name: 'remarks', width: 120},
					{ label: '校验类型', name: 'validType', width: 120, formatter:'select', editable: true,
					    edittype: "select",
					    editoptions: {
					        value: ":不验证;*:必填;n:数字;s:字符串;p:邮政编码;m:手机号码;e:电子邮件;url:网址;idcard:身份证"
					}},
					{ label: '验证规则', name: 'regexValid', width: 100, editable: true},
					{ label: '为空提示', name: 'nullmsg', width: 120, editable: true},
					{ label: '最小长度', name: 'minSize', width: 80, editable: true,editrules: {
						number: true
	             }},
					{ label: '最大长度', name: 'maxSize', width: 80, editable: true,editrules: {
						number: true
	             }},
	             { label: '最小值', name: 'minValue', width: 80, editable: true},
	             { label: '最大值', name: 'maxValue', width: 80, editable: true}
	  ];

	initGrid('validInfoTable',validInfoColModel,data);
	
	$("#attributeInfoTable").jqGrid('sortableRows',{
		update:function(){
			//动态的更改行
			var datas=getRowDatas("attributeInfoTable",true);
			//刷新
			//传入查询条件参数  
		$("#pageInfoTable").jqGrid('setGridParam',{  
			data:datas 
		}).trigger("reloadGrid"); //重新载入    
		//传入查询条件参数  
		$("#validInfoTable").jqGrid('setGridParam',{  
			data:datas 
		}).trigger("reloadGrid"); //重新载入    
		}
	});

	var lastSelection="";
	function editRow(id) {
		if (id && id !== lastSelection) {
			var grid = $("#attributeInfoTable");
			grid.jqGrid('restoreRow',lastSelection);
			grid.jqGrid('editRow',id, {keys:true, focusField: 4});
			lastSelection = id;
		}
	}	
}

//添加行数据
function addRowData(gridId){ //创建一条空的记录，待编辑  
    var gridObject = $('#'+gridId);  
    //获取表格的初始model    
    var colModel = gridObject.jqGrid().getGridParam("colModel");    
    var dataRow = JSON.stringify(colModel);   
    //var ids = gridObject.jqGrid('getDataIDs');    
    //如果jqgrid中没有数据 定义行号为1 ，否则取当前最大行号+1    
    var rowid ="insertrow"+random(6);
    gridObject.jqGrid("addRowData", rowid, dataRow, "last"); 
}  
//删除行
function delRowData(gridId){
	var ids = [];
	var rows =$("#"+gridId).jqGrid('getGridParam','selarrrow');
	var rowData= $("#"+gridId).jqGrid('getGridParam','selrow');
	var multiselect=$("#"+gridId).jqGrid('getGridParam','multiselect');
	if(!multiselect)
	{
		if(rowData)
		{
			rows[0]=rowData;
		}
	}
	if(rows.length==0){
          alert("请选择要删除的行");
          return;
    }
	var len = rows.length;  
	for ( var i = 0; i < len; i++) {
		 var rowid=rows[0];
		 $("#"+gridId).jqGrid("delRowData", rowid);   
	}
}

function getGridRowData(gridId,rowid){
	var gridObject = $("#"+gridId);  
	gridObject.saveRow(rowid, false, 'clientArray');
	var rowData=gridObject.jqGrid('getRowData',rowid);
	gridObject.editRow(rowid, true); 
	return rowData;
}

function random(length){
	var rand = "";
	for(var i = 0; i < length; i++){
	    var r = Math.floor(Math.random() * 10);
	    rand += r;
	}
	return rand;
}

function save(){
	var param = {};
	param.columnsStr = JSON.stringify(initTableData);
	param.id = $('#id').val();
	param.tableName = $('#tableName').val();
	param.className = $('#className').val();
	param.tableType = $('#tableType').val();
	param.remarks = $('#remarks').val();
	param.columnList = initTableData;
	var url = "../codegentable/save";
	$.ajax({
		type: "POST",
	    url: url,
	    traditional :true,  
	    contentType: "application/json",
	    data: JSON.stringify(param),
	    success: function(r){
	    	if(r.code === 0){
				alert('操作成功', function(index){
					location.reload();
				});
			}else{
				alert(r.msg);
			}
		}
	});
}

/**
 * 代码生成
 * @author han
 */
function codegen(){
	var ids = [];
	ids.push($('#id').val());
	location.href = "../codegentable/createCode?ids=" + JSON.stringify(ids);
}
</script>
<!-- <script src="../public/js/generator/codegentableEdit.js"></script> -->
</html>